package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.Classcardservice.ClassCardFieldService;
import com.wuseguang.springcloud.Classcardservice.ClassCardService;
import com.wuseguang.springcloud.JdbcTemplate.HaiweidaCooperativeSchoolJdbc;
import com.wuseguang.springcloud.dao.jdbc.StudentFacesTwoJdbc;
import com.wuseguang.springcloud.dao.repository.StudentFacesRegistrationRepository;
import com.wuseguang.springcloud.dao.repository.StudentFacesTwoRepository;

import com.wuseguang.springcloud.entity.StudentFacesTwo;
import com.wuseguang.springcloud.service.StudentFacesTwoService;
import com.wuseguang.springcloud.thread.FacePackThread;
import com.wuseguang.springcloud.thread.HaiweidaFacesThread;
import com.wuseguang.springcloud.thread.HeartbeatThread;
import com.wuseguang.springcloud.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 学生人脸2.0表 服务实现类
 * </p>
 *
 * @author
 * @since 2020-08-03
 */
@Service
public class StudentFacesTwoServiceImpl implements StudentFacesTwoService {


    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private StudentFacesTwoRepository studentFacesTwoRepository;
    @Autowired
    private StudentFacesRegistrationRepository studentFacesRegistrationRepository;
    @Autowired
    private StudentFacesTwoJdbc studentFacesTwoJdbc;
    @Autowired
    private ClassCardService classCardServiceImpl;
    @Autowired
    private ClassCardFieldService classCardFieldServiceImpl;
    @Autowired
    private HaiweidaCooperativeSchoolJdbc haiweidaCooperativeSchoolJdbc;

    @Override
    public Result findClassStudentFacesTwo(Integer classid, String schoolId) {
        logger.info("查询学生班级人脸注册情况");

        //查询班级人脸上传出情况
        List<Map<String, Object>> studentList = studentFacesTwoRepository.findbyClassId(classid);

        //查询学校的班牌
        Integer bancard = studentFacesRegistrationRepository.findCountBancard(schoolId);

        //循环人脸
        for (int i = 0; i < studentList.size(); i++) {

            //获取map
            Map<String, Object> map = studentList.get(i);
            //重新new一个map集合
            Map<String, Object> newMap = new HashMap<>(map);

            if (bancard != 0) {
                //查询班级注册情况
                List<Map<String, Object>> claaList = studentFacesRegistrationRepository.findBystudentFacesId(StringUtils.isEmpty(map.get("student_faces_id")) ? "0" : map.get("student_faces_id").toString(),
                        Integer.valueOf(schoolId));
                Integer count = studentFacesRegistrationRepository.findCountStudentFaces(StringUtils.isEmpty(map.get("student_faces_id")) ? "0" : map.get("student_faces_id").toString(),
                        Integer.valueOf(schoolId));
                newMap.put("claaList", claaList);
                newMap.put("state", claaList.size() == count ? 0 : 1);
            } else {
                newMap.put("claaList", new ArrayList<>());
                newMap.put("state", 1);
            }
            studentList.set(i, newMap);
        }

        return new Result(studentList);
    }

    @Override
    public Result addSutdentFacesTwo(StudentFacesTwo studentFacesTwo) {


        StudentFacesTwo studentFaces = studentFacesTwoRepository.findByStudentId(studentFacesTwo.getStudentId());
        if (!StringUtils.isEmpty(studentFaces)) {


            studentFacesRegistrationRepository.deleteByStudentFacesId(studentFaces.getId());
            //创建修改工具
            UpdateTool.copyNullProperties(studentFaces, studentFacesTwo);
        }
        logger.info("添加学生人脸");
        //学生上传的人脸
        Integer id = studentFacesTwoRepository.save(studentFacesTwo).getId();
        studentFacesTwoJdbc.insertClassStudentFaces(id, studentFacesTwo.getSchoolId());


        //把人脸同步到海威达
        Map<String, Object> map = new HashMap<>();
        map.put("userId", studentFacesTwo.getStudentId());
        map.put("photoUrl", studentFacesTwo.getUrl());
        map.put("type", "student");

        //创建线程，让线程去同步海威达人脸
        HaiweidaFacesThread h = new HaiweidaFacesThread();
        h.setMap(map);
        h.setSchoolId(studentFacesTwo.getSchoolId().toString());
        Thread thread = new Thread(h);
        //开启线程
        thread.start();


        return new Result();
    }

    @Override
    public Result delateStudentFacesTwo(String studentId, String schoolId) {

        logger.info("删除学生人脸");
        studentFacesTwoJdbc.updateClassStuentFaces(studentId);
        String sql = "select  deviceid from  student_faces_registration where school_id = ? and state = 3 GROUP BY deviceid";
        //查询要删除的班级数据
        List<String> classList = studentFacesTwoJdbc.queryListString(sql, new Object[]{schoolId});
        //开启线程推送
        HeartbeatThread ht = new HeartbeatThread(classList,"delfaceflag", "1");
        Thread thread = new Thread(ht);
        thread.start();
        return new Result();
    }

    @Override
    public Result stuentFacesRegisterTwo(String schoolId) {
        logger.info("注册学生人脸");
        String sql = "select  deviceid from  student_faces_registration where school_id = ? and state = 1 GROUP BY deviceid";
        //查询要删除的班级数据
        List<String> classList = studentFacesTwoJdbc.queryListString(sql, new Object[]{schoolId});
        //修改班级心跳
        classCardFieldServiceImpl.deviceidAndCards(classList, "faceflag", "1");
        //推送
        classCardServiceImpl.deviceidAndCards(classList);
        return new Result();
    }

    @Override
    public Result importStudentFaces(MultipartFile uploadFile, String schoolId) {
        logger.info("批量导入人脸");


        try {
            //解压解压文件到项目中
            ZipUncompress.unZipFiles(FileUtil.MultipartFileToFile(uploadFile), "");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //文件名称
        String uploadFileName = uploadFile.getOriginalFilename().substring(0, uploadFile.getOriginalFilename().indexOf("."));
        //创建人脸导入线程
        FacePackThread fpt = new FacePackThread(uploadFileName, schoolId);
        //创建线程
        Thread thread = new Thread(fpt);
        thread.start();

        return new Result();
    }

    @Override
    public Result importStudentFaces(String schoolId) {
        logger.info("批量导入人脸");


        //创建人脸导入线程
        FacePackThread fpt = new FacePackThread("26",schoolId);
        //创建线程
        Thread thread = new Thread(fpt);
        thread.start();

        return new Result();
    }

 /*   @Override
    public Result synchronousFacesTwo(String gradeId) {
//        String sql="SELECT t.id userId,w.url photoUrl,'student' as type FROM student_faces_two w,student t,classes s WHERE  w.student_id=t.id AND  " +
//                "  w.school_id=t.school_id AND  t.class_id=s.id AND grade_id=?   GROUP BY t.id";
//
//
//        List<Map<String, Object>> maps = studentFacesTwoJdbc.queryListMap(sql, gradeId);


        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
        //人俩Map
        Map<String, Object> facesMap = new HashMap<>();
        facesMap.put("userId", 26765);
        facesMap.put("photoUrl", "https://oss.yuguozhijia.online/30/picture/7285dbb703984183951be0cfee5685c2.JPG");
        facesMap.put("type", "student");
        maps.add(facesMap);


        String s = haiweidaStudentFacesTwo(maps, "30");


        return new Result(s);
    }*/





    public Map<String, Object> tokenMapTwo(Map<String, Object> map) {
        try {
            //刷新token
            Map<String, Object> tokenMap = HaiweidaUtil.login(map.get("school_code").toString(),
                    map.get("user_name").toString(), map.get("password").toString());

            String uuid = tokenMap.get("uuid").toString();
            String expTime = tokenMap.get("expTime").toString();
            String token = "JWT " + tokenMap.get("token").toString();
            //获取时间
            Date d = new Date(System.currentTimeMillis() + (Integer.valueOf(expTime) * 1000) - 60000);
            //修改过期token
            String sql = "UPDATE `haiweida_cooperative_school` SET `token` = ?, `exp_time` = ?, `uuid` = ? WHERE `id` = ? ";
            studentFacesTwoJdbc.updateByParameter(sql, token, d, uuid, map.get("id").toString());
            tokenMap.put("token", "JWT " + tokenMap.get("token"));
            return tokenMap;
        } catch (Exception e) {
            logger.info("token 为空");
            return null;
        }
    }
}
